/* eslint-disable @typescript-eslint/ban-ts-comment */
// @ts-nocheck
import React, { useCallback, useMemo } from 'react'
import Taro from '@tarojs/taro'
import { Button } from '@tarojs/components'
import { useSelector, useDispatch } from 'react-redux'
import { getPlatform, showToast } from '@UTILS/common'
import debounce from 'lodash.debounce'
import Navigate from '@NAVIGATION/navigateManager'
import authActions from '@ACTIONS/auth'
import { Analytic_Type } from '@CONSTANTS/analytic'
import { getUserInfo, getJsCode } from '@UTILS/wx'
import style from './LoginVerifyBtn.module.scss'

const { isWeb, isWX } = getPlatform()
interface Props {
  onClick?: (bool?: boolean) => void
  showLogin?: () => void
  className?: string
  eventId?: string
  eventParams?: unknown
  sceneData?: unknown
  disabledVerify?: boolean
  disabled?: boolean
  loading?: boolean
  isPhoneVerify?: boolean
  loginSuccess?: () => void
}

// eventId  拦截未登录情况下，执行埋点
const LoginVerifyBtn: React.FC<Props> = ({
  children, showLogin, onClick, className, eventId,
  eventParams, disabledVerify = false, disabled, loading,
  isPhoneVerify = false, sceneData, loginSuccess
}) => {
  const dispatch = useDispatch()
  const { dispatchWeChatLogin, dispatchLoginWeiXin, dispatchSetLoginSuccessInfo } = authActions
  const isVisitor = useSelector(state => state.profile.isVisitor)
  const openType = useMemo(() => {
    if (isVisitor && !disabledVerify) {
      return isPhoneVerify ? 'getPhoneNumber' : 'getUserInfo'
    }
    return ''
  }, [isVisitor, disabledVerify, isPhoneVerify])

  const weChatLogin = useCallback(params => dispatch(dispatchWeChatLogin(params)), [dispatch, dispatchWeChatLogin])
  const setLoginSuccessInfo = useCallback(successCallBack => dispatch(dispatchSetLoginSuccessInfo(successCallBack)),
    [dispatch, dispatchSetLoginSuccessInfo])
  const weChatPhoneLogin = useCallback(
    (params, callback, disabledBack) => dispatch(dispatchLoginWeiXin({ payload: params, callback, disabledBack })),
    [dispatch, dispatchLoginWeiXin]
  )

  const onGetUserInfoFunc = useCallback(
    async res => {
      setLoginSuccessInfo(loginSuccess)
      if (!res.detail.cloudID) {
        Navigate.authPage()
        return
      }
      Taro.showLoading({ title: '登录中' })
      try {
        const userInfo = await getUserInfo(res.detail.cloudID)
        weChatLogin({ UserInfo: userInfo })
      } catch (e) {
        Taro.hideLoading()
        showToast('登录失败')
        Navigate.authPage()
      }
    }, [loginSuccess, setLoginSuccessInfo, weChatLogin]
  )

  const phoneLoginSuccess = useCallback(() => onClick?.(true), [onClick])

  const onGetPhoneNumberFunc = debounce(
    useCallback(
      async res => {
        const phoneData = res.detail
        if (phoneData.errMsg !== 'getPhoneNumber:ok') return
        const { encryptedData, iv } = phoneData
        const code = await getJsCode()
        const payload = { encrypted_data: encryptedData, iv, code }
        weChatPhoneLogin(payload, phoneLoginSuccess, true)
      },
      [phoneLoginSuccess, weChatPhoneLogin]
    ),
    1000,
    { leading: true, trailing: false }
  )

  const onClickFunc = debounce(
    useCallback(
      e => {
        e?.stopPropagation?.()
        if (disabled) return
        if (!isVisitor || disabledVerify) {
          onClick?.()
          return
        }
        if (Analytic_Type[eventId]?.eventId) {
          Taro.tracker.trackEvent(Analytic_Type[eventId].eventId, eventParams, sceneData)
        }
        if (isWeb) {
          showLogin?.()
          setLoginSuccessInfo(loginSuccess)
        } else if (!isWX) {
          setLoginSuccessInfo(loginSuccess)
          Navigate.authPage()
        }
      },
      [disabled, isVisitor, disabledVerify, eventId, onClick, eventParams, sceneData, showLogin, loginSuccess, setLoginSuccessInfo]
    ),
    1000,
    { leading: true, trailing: false }
  )

  return (
    <Button
      disabled={disabled}
      onClick={onClickFunc}
      openType={openType}
      onGetUserInfo={onGetUserInfoFunc}
      onGetPhoneNumber={onGetPhoneNumberFunc}
      loading={loading}
      className={`${style.loginVerifyBtn} ${className || ''}`}
      hoverClass="none"
    >
      {children}
    </Button>
  )
}

export default LoginVerifyBtn
